package com.igo.onepack.reinforce;

import com.igo.onepack.utils.CMDUtils;
import com.igo.onepack.utils.FileUtils;
import com.igo.onepack.utils.Log;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

class LeguReinforce extends AbstractReinforce {

    private static final String TAG = "LeguReinforce";

    private final String leguSecretId;
    private final String leguSecretKey;

    private File shieldJar;

    LeguReinforce(Properties properties) {
        this.leguSecretId = properties.getProperty("legu.secretId");
        this.leguSecretKey = properties.getProperty("legu.secretKey");
    }

    private void prepareShieldJarFile() throws ReinforceException {
        shieldJar = new File(FileUtils.getUserTempDir(),"onepack/ms-shield-1.0.3.jar");
        if (!FileUtils.isFile(shieldJar)) {
            try {
                FileUtils.copyResourcesFile("ms-shield-1.0.3.jar",shieldJar);
            } catch (IOException e) {
                throw new ReinforceException(e);
            }
        }
    }

    @Override
    public File onReinforce(File apkFile) throws ReinforceException {
        prepareShieldJarFile();
        return commitReinforce(apkFile);
    }

    /**
     * 提交加固请求
     * @param apkFile apk file
     * @return 加固完成会返回一个加固的apk
     */
    private File commitReinforce(File apkFile) throws ReinforceException {
        CMDUtils.exec(new CMDUtils.Callback() {
            @Override
            public void onStartExec() {
                Log.d(TAG,String.format("开始加固 %s",apkFile.getName()));
            }

            @Override
            public void onStopExec() {
                Log.d(TAG,String.format("加固结束 %s",apkFile.getName()));
            }
        },"java","-jar",shieldJar.getAbsolutePath(),
                "-sid",leguSecretId,"-skey",leguSecretKey,
                "-uploadPath",apkFile.getAbsolutePath(),"-downloadPath",getOutDir().getAbsolutePath());
        return new File(getOutDir(),FileUtils.makeApkName(apkFile,"legu"));
    }
}